package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;


import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Permission;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.PermissionMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private PermissionMapper permissionMapper;


    // 根据角色ID查询权限(只要权限码)
    @Override
    public List<String> selectPermissionById(Long id) {
        List<Permission> permissions = permissionMapper.selectPermissionByRoleId(id);
        System.out.println("Mapper返回的权限"+permissions);
        return permissions.stream()
                .map(Permission::getPermissionCode)
                .collect(Collectors.toList());
    }



    @Override
    public List<Permission> selectPermissionTree() {
        // 1. 查询所有权限（已按层级排序）
        List<Permission> allPermissions = permissionMapper.selectPermissionTree();

        // 2. 组装树结构
        return buildPermissionTree(allPermissions);
    }

    /**
     * 组装权限树
     */
    private List<Permission> buildPermissionTree(List<Permission> permissions) {
        if (permissions == null || permissions.isEmpty()) {
            return new ArrayList<>();
        }

        // 转换为ID-对象映射表
        Map<Long, Permission> permissionMap = permissions.stream()
                .collect(Collectors.toMap(Permission::getId, p -> p));

        // 构建树结构
        List<Permission> tree = new ArrayList<>();
        for (Permission permission : permissions) {
            Long parentId = permission.getParentId();
            if (parentId == null || parentId == 0) {
                // 父节点为空，作为根节点
                tree.add(permission);
            } else {
                // 将当前节点添加到父节点的children列表
                Permission parent = permissionMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(permission);
                }
            }
        }
        return tree;
    }
}